<template>
    <div>
     <el-scrollbar class="app-container-scroll-bar" >
        <pageTitle :title="pageTitle" :hasBack="true"></pageTitle>
        
        <!-- 规则 -->
       <div class="wrap">
          <span style="margin-left: 25px;font-size: 18px;color: rgb(96, 98, 102);">关联资源</span>

        <el-form   :model="form" :rules="rules" ref="ruleForm"  label-width="120px">
                    <el-form-item label="资源类型" prop="monitorType" style="margin:20px 0;">
                        <el-select  size="small" v-model="form.monitorType" 
                            @change="handleChooseType(form.monitorType)">
                            <el-option :label="item.name" :value="item.value" v-for="item in monitorTypeList" :key="item.index"></el-option>
                        </el-select>
                    </el-form-item>
             
                  <span style="margin-left: 25px;font-size:16px;color: rgb(96, 98, 102);">设置规则</span>

             
                <el-form-item label="规则名称" prop="name" style="margin:20px 0;">
                    <el-input style="width:200px;" size="small"  v-model="form.name"></el-input>
                </el-form-item>
   
                <el-form-item label="添加规则" prop="name">
                    <table  class="dialog-table">
                        <tr>
                            <th>规则描述</th>
                            <th>参照类型</th>
                            <th style="width:100px">运算符</th>
                            <th style="width:100px">阀值</th>
                            <th >单位</th>
                            <th style="width:120px">监控频率/分钟</th>
                            <th>监控指标</th>
                            <th>发生次数</th>
                            <th style="width:130px">操作</th>
                        </tr>
                        <tr>
                            <td>
                                <el-select   v-model="form.norm" @change="handleChooseNorm(form.norm)" :disabled="disabled2">
                                    <el-option :label="item.name" :value="item.value" v-for="item in monitor_norm" :key="item.index"></el-option>
                                </el-select>
                            </td>
                            <td>
                                <el-form-item prop="refrenceType" style="height:24px;"  v-if="isShow2" >
                                    <el-select  v-model="form.refrenceType" @change="handleChooseReType(form.refrenceType)" :disabled="disabled3" style="width:85px;">
                                        <el-option :label="item.name" :value="item.value" v-for="item in refrence_type" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item prop="refrenceType" style="height:24px;" v-if="!isShow2" >
                                    <el-input style="width:85px;" disabled v-model="text"></el-input>
                                </el-form-item>
                            </td>
                            <td>
                                <el-form-item prop="comparison" style="height:24px;">
                                    <el-select   v-model="form.comparison">
                                        <el-option  :label="item.name" :value="item.value" v-for="item in comparison" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                             <td>
                                <el-form-item prop="threshold" style="height:24px;">
                                    <el-input  placeholder="阀值" v-model="form.threshold" @blur="checkFz(form.threshold)" type="number"></el-input>
                                </el-form-item>
                            </td>
                             <td>
                                <el-form-item prop="unitType" style="height:24px;" v-if="isShow" >
                                    <el-select  style="width:80px" placeholder="单位"  v-model="form.unitType">
                                        <el-option :value="item.value" :label="item.name" v-for="item in unit_type" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item prop="unitType" style="height:24px;" v-if="!isShow" >
                                    <el-input v-if="!isShow" v-model="form.unitType" style="width:80px"  disabled></el-input>
                                </el-form-item>
                            </td>
                            <td>
                                <el-form-item prop="frequency" style="height:24px;">
                                    <el-select   v-model="form.frequency">
                                        <el-option :label="item.name" :value="item.value" v-for="item in monitor_frequency" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                            <td>
                                <el-form-item prop="frequencyType" style="height:24px;">
                                    <el-select   v-model="form.frequencyType">
                                        <el-option :label="item.name" :value="item.value" v-for="item in frequency_type" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                            <td>
                                <el-form-item prop="times" style="height:24px;" >
                                    <el-select
                                        
                                        v-model="form.times"
                                        filterable
                                        allow-create
                                        default-first-option
                                        placeholder="请选择">
                                        <el-option  :label="item.name" 
                                                    :value="item.value" 
                                                    v-for="item in appear_time" 
                                                    :key="item.index"
                                                ></el-option>
                                    </el-select> 
                                 </el-form-item>
                            </td>
                            <td>
                                <el-button type="text" size="small"  @click="hanleAddBtn">确认添加</el-button>
                            </td>
                        </tr>
                        <!-- 新增的行 -->
                        <tr v-for="(item,index) in alarmRuleDetails" :key="item.index" v-if="alarmRuleDetails.length != 0">
                            <td>{{item.alarmRuleDetails2}}</td>
                            <td>{{item.refrenceType2}}</td>
                            <td>{{item.comparison}}</td>
                             <td>{{item.threshold}}</td>
                            <td>{{item.unitType}}</td>
                            <td>{{item.frequency}}</td>
                            <td>{{item.norm2}}</td>
                            <td>{{item.times}}</td>
                            <td>
                                <el-button type="text" size="small" @click="handleDelete(index)">删除</el-button>
                            </td>
                        </tr>
                        <!-- 根据id获取的自己的ruler行 -->
                        <tr v-for="(item,index) in myselfRulerList" :key="item.index" v-if="myselfRulerList.length != 0">
                            <td>{{item.alarmRuleDetails3}}</td>
                            <td>{{item.refrenceType3}}</td>
                            <td>{{item.comparison}}</td>
                            <td>{{item.threshold}}</td>
                            <td>{{item.unitType}}</td>
                            <td>{{item.frequency}}</td>
                            <td>{{item.norm3}}</td>
                            <td>{{item.times}}</td>
                            <td>
                                <el-button type="text" size="small" @click="handleDelete2(index)">删除</el-button>
                            </td>
                        </tr>
                    </table>
               </el-form-item>
           
              <span style="margin-left: 25px;font-size: 18px;color: rgb(96, 98, 102);">通知规则</span>
           
            <el-form-item label="告警级别" style="margin:20px 0">
                <el-select v-model="form.level">
                    <el-option v-for="item in alarm_level" :key="item.index" :value="item.value" :label="item.name + '级'"></el-option>
                </el-select>
            </el-form-item>
            
            <el-form-item label="通知对象">
                <el-select size="small"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="输入联系人"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    v-model="form.noticeLinkman"
                    @change="handleChoosePeople(form.noticeLinkman)" value-key="linkName">
                    <el-option   v-for="item in lxpeoeleList" 
                                :value="item" 
                                :label="item.linkName"
                                :key="item.index"
                                :disabled="item.d"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label=" ">
                <el-tag closable v-for="(item,index) in choosePeople"  :key="item.index"  @close="handleClose(index,item)" type="info" style="margin-left:4px;font-size:12px;">
                    {{item.linkName}}
                </el-tag>
                <el-tag closable v-for="(item,index) in myselfPopleList"  :key="item.index"  @close="handleClose2(index,item)" type="info" style="margin-left:4px;font-size:12px;">
                    {{item.linkName}}
                </el-tag>
            </el-form-item>
         
            <el-form-item label="通知方式">
                <el-checkbox-group  v-model="form.noticeType">
                    <el-checkbox label="1" >邮箱</el-checkbox>
                    <!-- <el-checkbox label="2">短信</el-checkbox> -->
                </el-checkbox-group>
            </el-form-item>
            
            

           <el-form-item label="通知频率" prop="noticeRate">
                <el-radio-group   v-model="form.noticeRate">
                    <el-radio label="1">每次</el-radio>
                    <el-radio label="2">每小时</el-radio>
                    <el-radio label="3">不通知</el-radio>
                </el-radio-group>
            </el-form-item>
 
            <el-form-item style="margin-top:20px;">
                <el-button type="primary" @click="onSubmit">更新修改</el-button>
                <el-button @click="returnbtn">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
    </el-scrollbar>
    </div>
</template>


<script>
import pageTitle from "@/view/layout/components/content/pageTitle";
import {
    getDicInfo,
    getAlarmRulesInfo,
    pageAlarmContactMan,
    updateAlarmRule} from "@/service/swagger/AlarmController"
export default {
    components: {
        pageTitle
    },
    data() {
        return {
            //页面主标题
            pageTitle: "修改告警规则",
            isShow2: true,
            text: '监控比',
            deleteRuleDetailId: [],
            tagNorm: '',
            disabled2: false,
            disabled3: false,
            monitorTypeList: [
                { value: 0, name: '主机' },
                { value: 1, name: '容器' }
            ],
            myselfPopleList: [],
            myselfRulerList: [],
            id: this.$route.query.id,
            choosePeople: [],
            isShow: true,
            alarm_level: [],
            refrence_type: [],
            unit_type: [],
            copy_monitor_norm: [],
            monitor_norm: [],
            comparison: [],
            monitor_frequency: [],
            frequency_type: [],
            appear_time: [],
            alarm_notify_type: '',
            alarm_notice_rate: '',
            loading: false,
            lxpeoeleList: [],
            alarmRuleDetails: [],//警告规则列表
            form: {
                refrenceType: '',//监控值  监控比
                unitType: '',//单位
                name: '',//规则名称 
                alarmRuleDetails: '',//报警规则描述
                comparison: '',//运算发
                threshold: '',//阀
                frequency: '',//出现频率
                frequencyType: '',//出现方式
                norm: '',//描述
                times: '',//次数
                level: '',//警告级别，
                monitorTarget: '',//监控目标，主机IP、容器ID、应用实例编号等
                monitorType: '',//监控资源类型 0：主机 1：容器 2：应用 
                noticeConten: '',//通知内容 
                noticeLinkman: '',//通知人ID 
                noticeRate: '',//通知频率，不能为空 
                noticeType: [],//通知方式
            },
            // 规则
            rules: {
                refrenceType: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                comparison: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                threshold: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                unitType: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                frequency: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                frequencyType: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                times: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                noticeRate: [
                    { required: true, message: '请选择通知频率', trigger: 'blur' }
                ]
            }

        }
    },
    created() {
        //获得联系人列表
        pageAlarmContactMan({}).then(ret => {
            //    console.log(ret)
            if (ret.code === 0) {
                ret.data.data.forEach(el => {
                    el.d = false
                })
                this.lxpeoeleList = ret.data.data
            }
        })

        //获取规则字典
        getDicInfo().then(ret => {
            // console.log(ret)
            if (ret.code === 0) {
                this.alarm_level = ret.data.alarm_level //告警级别
                this.alarm_notice_rate = ret.data.alarm_notice_rate,//通知频率组
                    this.alarm_notify_type = ret.data.alarm_notify_type,//通知方式组
                    this.appear_time = ret.data.appear_time,//频率出现次数
                    this.comparison = ret.data.comparison,//比较运算符
                    this.frequency_type = ret.data.frequency_type,//出现方式
                    this.monitor_frequency = ret.data.monitor_frequency,//监控频率
                    this.monitor_norm = ret.data.monitor_norm,//规则描述
                    this.copy_monitor_norm = ret.data.monitor_norm,//规则描述copy
                    this.unit_type = ret.data.unit_type
                this.refrence_type = ret.data.refrence_type
                this.form.frequencyType = ret.data.frequency_type[0].value
            }
        })

    },
    mounted() {
        // 根据id获取对应规则
        getAlarmRulesInfo(this.id).then(ret => {
            // console.log(ret)
            if (ret.code === 0) {
                ret.data.alarmRuleDetails.forEach(el => {
                    el.norm = ret.data.norm
                    if (el.norm === 'cpu_usage') {
                        el.alarmRuleDetails3 = 'cpu使用率'
                    } else if (el.norm === 'disk_usage') {
                        el.alarmRuleDetails3 = '磁盘使用率'
                    } else if (el.norm === 'network_flow') {
                        el.alarmRuleDetails3 = '网络流量'
                    } else if (el.norm === 'ram_usage') {
                        el.alarmRuleDetails3 = '内存使用率'
                    }

                    if (el.refrenceType === 1) {
                        el.refrenceType3 = '监控值'
                    } else if (el.refrenceType === 2) {
                        el.refrenceType3 = '监控比'
                    }

                    if (el.frequencyType === 1) {
                        el.norm3 = '连续出现'
                    } else if (el.frequencyType === 2) {
                        el.norm3 = '共计出现'
                    }
                })
                this.form.monitorType = ret.data.monitorType //资源类型
                if (ret.data.monitorType == 1) {
                    //    如果是容器规则描述则去除磁盘使用率
                    let newnorm = this.monitor_norm.filter(el => {
                        return el.code != "disk_usage"
                    })
                    this.monitor_norm = newnorm
                }
                this.form.name = ret.data.name //规则名称
                this.form.level = ret.data.level + ''//警告规则

                //  如果自己的联系人列表id 等于 所有联系人列表的id 禁止选择
                ret.data.alarmLinkmens.forEach(el => {
                    this.lxpeoeleList.forEach(it => {
                        if (el.userId == it.userId) {
                            it.d = true
                        }
                    })
                })

                this.myselfPopleList = ret.data.alarmLinkmens //联系人
                this.form.noticeType = ret.data.noticeTypes //联系方式
                this.form.noticeRate = ret.data.noticeRate  //联系频率
                this.myselfRulerList = ret.data.alarmRuleDetails //规则列表

                this.tagNorm = ret.data.alarmRuleDetails[0].norm//用于判断添加的规则是否与自己本身的规则描述一样

                if (ret.data.alarmRuleDetails[0].norm === 'cpu_usage') {
                    this.form.norm = ret.data.alarmRuleDetails[0].norm
                    this.disabled3 = true
                    this.form.refrenceType = '2'
                    this.isShow = false
                    this.form.unitType = '%'
                    this.isShow2 = false
                } else {
                    this.disabled3 = false
                    this.form.unitType = ''
                    this.isShow = true
                    this.form.refrenceType = '1'
                    this.isShow2 = true
                }
            }
        })


    },
    updated() {
        // 当添加列表清空时候
        if (this.alarmRuleDetails.length === 0) {
            this.disabled2 = false
            this.disabled3 = false
        }
    },
    methods: {
        // 修改规则
        onSubmit() {
            // 自己的规则列表加上新增的规则列表
            let newarr = this.alarmRuleDetails.concat(this.myselfRulerList)
            if (newarr.length != 0 && this.form.name != '') {
                // 去除没用的字段
                this.alarmRuleDetails.forEach(el => {
                    for (var key in el) {
                        delete el['alarmRuleDetails2']
                        delete el['norm2']
                        delete el['refrenceType2']
                        delete el['name']
                    }
                })
                this.myselfRulerList.forEach(el => {
                    for (var key in el) {
                        delete el['alarmRuleDetails3']
                        delete el['refrenceType3']
                    }
                })

                //联系人id数组
                let noticeLinkman = []
                this.choosePeople.forEach(el => {
                    noticeLinkman.push(el.userId)
                })
                this.myselfPopleList.forEach(el => {
                    noticeLinkman.push(el.userId)
                })

                let params = {
                    deleteRuleDetailId: this.deleteRuleDetailId,
                    alarmRuleDetails: this.alarmRuleDetails.concat(this.myselfRulerList),
                    monitorTarget: this.form.monitorTarget,
                    monitorType: this.form.monitorType,
                    name: this.form.name,
                    noticeRate: this.form.noticeRate,
                    noticeType: this.form.noticeType,
                    noticeLinkman: noticeLinkman,
                    level: this.form.level,
                    noticeConten: this.noticeConten,
                    norm: this.form.norm,
                    id: this.id
                }
                // console.log(params)
                updateAlarmRule(params).then(ret => {
                    if (ret.code === 0) {
                        this.$message({
                            showClose: true,
                            message: '修改成功!',
                            type: 'success'
                        })
                        this.$router.push({
                            path: 'gz'
                        })
                    }
                })
            } else {
                this.$message.error('请检查是否已添加规则和规则名称是否填写！')
                return false;
            }

        },
        //选容器时候去除规则描述的磁盘使用率
        handleChooseType(val) {
            if (val == 1) {
                let newnorm = this.monitor_norm.filter(el => {
                    return el.code != "disk_usage"
                })
                this.monitor_norm = newnorm
            } else {
                this.monitor_norm = this.copy_monitor_norm
            }
        },
        // 检查数字
        checkFz(val) {
            let reg = new RegExp(/^[1-9]\d*(\.\d+)?$/)
            if (!val.match(reg)) {
                this.form.threshold = ''
            }
        },
        // 选择cup使用率 默认监控比
        handleChooseNorm(type) {
            if (type === 'cpu_usage') {
                this.disabled3 = true
                this.form.refrenceType = '2'
                this.isShow = false
                this.isShow2 = false
                this.form.unitType = '%'
            } else {
                this.disabled3 = false
                this.form.unitType = ''
                this.isShow = true
                this.isShow2 = true
                this.form.refrenceType = '1'
            }
        },
        // 选择监控值 或者监控比单位变化
        handleChooseReType(val) {
            if (val === '1') {
                this.form.unitType = ''
                this.isShow = true
            } else if (val === '2') {
                this.isShow = false
                this.form.unitType = '%'
            }
        },
        //选择联系人 去重
        handleChoosePeople(val) {
            val.d = true
            this.form.noticeLinkman = ''
            this.choosePeople.push(val)
        },
        handleClose(index, item) {
            this.lxpeoeleList.forEach(el => {
                if (el.userId == item.userId) {
                    el.d = false
                }
            })
            this.choosePeople.splice(index, 1);
        },
        handleClose2(index, item) {
            this.lxpeoeleList.forEach(el => {
                if (el.userId == item.userId) {
                    el.d = false
                }
            })
            this.myselfPopleList.splice(index, 1);
        },
        //添加警告规则
        hanleAddBtn() {
            if (this.form.norm != this.tagNorm && this.myselfRulerList.length != 0) {
                this.$message({ message: '规则描述必须一致!', type: 'error' })
            } else {
                this.disabled2 = true
                let ruler = {
                    name: this.form.name,
                    norm: this.form.norm,
                    refrenceType: this.form.refrenceType,
                    comparison: this.form.comparison,
                    threshold: this.form.threshold,
                    frequency: this.form.frequency,
                    unitType: this.form.unitType,
                    times: this.form.times,
                    frequencyType: this.form.frequencyType
                }

                if (ruler.norm === 'cpu_usage') {
                    ruler.alarmRuleDetails2 = 'cpu使用率'
                } else if (ruler.norm === 'disk_usage') {
                    ruler.alarmRuleDetails2 = '磁盘使用率'
                } else if (ruler.norm === 'network_flow') {
                    ruler.alarmRuleDetails2 = '网络流量'
                } else if (ruler.norm === 'ram_usage') {
                    ruler.alarmRuleDetails2 = '内存使用率'
                }

                if (ruler.refrenceType === '1') {
                    ruler.refrenceType2 = '监控值'
                } else if (ruler.refrenceType === '2') {
                    ruler.refrenceType2 = '监控比'
                }

                if (ruler.frequencyType === '1') {
                    ruler.norm2 = '连续出现'
                } else if (ruler.frequencyType === '2') {
                    ruler.norm2 = '共计出现'
                }

                if (this.form.norm === 'cpu_usage') {
                    this.disabled3 = true
                } else {
                    this.disabled3 = false
                }

                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        this.alarmRuleDetails.push(ruler)
                        // this.form.refrenceType = '',//监控值  监控比
                        // this.form.unitType = '',//单位
                        this.form.comparison = ''//运算
                        this.form.threshold = ''//阀
                        this.form.frequency = ''//出现频率
                        // this.form.frequencyType = ''//出现方式
                        // this.form.norm = '',//描述
                        this.form.times = ''//次数
                    } else {
                        this.$message.error('规则填写不完整')
                    }
                })
            }
        },
        // 删除规则警告
        handleDelete(index) {
            this.alarmRuleDetails.splice(index, 1)
        },
        // 删除规则警告(自己的)
        handleDelete2(index) {
            this.deleteRuleDetailId.push(this.myselfRulerList[index].id)
            // console.log(this.deleteRuleDetailId)
            this.myselfRulerList.splice(index, 1)

        },
        // 远程搜索联系人
        remoteMethod(query) {
            let params = {
                linkName: query
            }
            if (query !== '') {
                this.loading = true;
                setTimeout(() => {
                    this.loading = false;
                    pageAlarmContactMan(params).then(ret => {
                        if (ret.code === 0) {
                            this.lxpeoeleList = ret.data.data
                        }
                    })
                }, 200)
            } else {
                this.lxpeoeleList = []
            }
        },
        returnbtn() {
            this.$router.go(-1)
        }
    }
}

</script>
<style scoped>
.dialog-table {
  width: 95%;
  text-align: center;
  border: 1px solid #ccc;
}
th {
  text-align: center;
  color: #999;
  background: #f5f6fb;
}
td {
}
tr {
  height: 30px;
}
.wrap{
  width: 100%; 
  margin-top: 25px
}
.el-input .el-input__suffix .el-icon-circle-close::before{
   	display:none !important;
}
.el-input .el-input__suffix .el-icon-circle-check::before{
   	display:none !important;
}
</style>
